package com.base.cn.platform.os.controller.web.user.center;

import com.base.cn.platform.os.common.WebBaseController;
import com.base.cn.platform.os.common.constants.CommonConstants;
import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.rsa.WebRsaUtils;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.action.ActionKey;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.user.AccountHistoryType;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import com.base.cn.platform.os.entity.user.integral.CusUserIntegralRecord;
import com.base.cn.platform.os.entity.user.integral.IntegralRule;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.user.account.CusUserAccountHistoryService;
import com.base.cn.platform.os.service.manage.user.account.CusUserAccountService;
import com.base.cn.platform.os.service.manage.user.address.CusUserAddressService;
import com.base.cn.platform.os.service.manage.user.integral.CusUserIntegralRecordService;
import com.base.cn.platform.os.service.manage.user.integral.CusUserIntegralRuleService;
import com.base.cn.platform.os.service.manage.user.integral.CusUserIntegralService;
import com.base.cn.platform.os.service.manage.user.login.UserLoginService;
import com.base.cn.platform.os.service.manage.user.member.CusUserMemberBuyRecordService;
import com.base.cn.platform.os.service.manage.user.member.CusUserMemberService;
import com.base.cn.platform.os.service.manage.user.user.CusUserService;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户个人中心Controller
 *
 * @author s.li
 * @create 2018-05-10-19:42
 */
@Controller
@RequestMapping("/web/uc")
public class UserCenterController extends WebBaseController {

    @Autowired
    private CusUserService cusUserService;
    @Autowired
    private CusUserAddressService cusUserAddressService;
    @Autowired
    private CusUserAccountService cusUserAccountService;
    @Autowired
    private CusUserAccountHistoryService cusUserAccountHistoryService;
    @Autowired
    private CusUserIntegralService cusUserIntegralService;
    @Autowired
    private CusUserIntegralRecordService cusUserIntegralRecordService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private CustomCacheChannel customCacheChannel;
    @Autowired
    private CusUserIntegralRuleService cusUserIntegralRuleService;

    @Autowired
    private CusUserMemberBuyRecordService cusUserMemberBuyRecordService;
    @Value("${mobile.path}")
    private String contextPath;

    /**
     * 我的资料详情
     * @param model
     * @return
     */
    @RequestMapping("/myInfo")
    public String  newMyInfo(HttpServletRequest request,Model model,
                             @RequestParam(value = "tag",required = false) String tag){
        BigDecimal userId= webMobileLoginUtil.getLoginUserId(request);
        Map<String, Object> user = cusUserService.userInfo(userId, false, false, false, false, false, false, false);
        model.addAttribute("user", user);
        model.addAttribute("tag", tag);
        return resultPage("/user/center/myInfo/u-baseUserInfo");
    }

    /**
     * 获取加密数据
     * @return
     * @throws Exception
     */
    @RequestMapping("/getKeyMap")
    @ResponseBody
    public Map<String,Object> getKeyMap() throws Exception{
        Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
        return ResultUtil.SUCCESS("获取成功",keyMap);
    }

    /**
     * 基础信息
     * @param model
     * @return
     */
    @RequestMapping("/ajax/baseUserInfo")
    public String baseNewUserInfo(HttpServletRequest request,Model model){
        BigDecimal userId= webMobileLoginUtil.getLoginUserId(request);
        Map<String, Object> user = cusUserService.userInfo(userId, false, false, false, false, false, false, false);
        model.addAttribute("user", user);
        return resultPage("/user/center/myInfo/u-myInfo");
    }


    /**
     * 个人中心修改个人资料
     * @param user 用户数据
     * @return
     */
    @RequestMapping("/ajax/saveUserPersonalData")
    @ResponseBody
    public Map<String,Object> saveNewUserPersonalData(HttpServletRequest request,
                                                      @RequestBody Map<String,Object> user){
        Map<String, Object> resultMap = cusUserService.updateUser(user);
        if (ResultUtil.getSuccess(resultMap)) {
            String  strUser =  (String)ResultUtil.getEntity(resultMap);
            String sid = WebUtils.getCookie(request, CommonConstants.USER_SINGLE_ID);
            //重新更新缓存
            userLoginService.updateUserLoginCache(sid,strUser);
        }
        return resultMap;
    }

    /**
     * 收货地址
     * @param request
     * @return
     */
    @RequestMapping("/ajax/myAddress")
    public String  myAddress(HttpServletRequest request,Model model){
        BigDecimal userId= webMobileLoginUtil.getLoginUserId(request);
        List<Map<String,Object>> userAddresses = new ArrayList<>();
        if (DataUtil.idIsNotNull(userId)){
            userAddresses =cusUserAddressService.queryUserAddressListByUserId(userId,true);
        }
        model.addAttribute("userAddresses",userAddresses);
        return resultPage("/user/center/myInfo/u-myAddress");
    }
     /**
     * 头像设置
     * @param request
     * @return
     */
    @RequestMapping("/ajax/setFaceImage")
    public String setFaceImage(HttpServletRequest request,Model model){
        BigDecimal userId= webMobileLoginUtil.getLoginUserId(request);
        Map<String,Object> user = cusUserService.userInfo(userId,false,false,false,false,false,false,false);
        model.addAttribute("userMap",user);
        return resultPage("/user/center/face/u-setFace");
    }

    /**
     * 保存用户头像
     * @param request
     * @param avatar 用户头像地址
     * @return Map<String,Object>
     */
    @RequestMapping("/saveUserAvatar")
    @ResponseBody
    public Map<String,Object> saveUserAvatar(HttpServletRequest request,
                                             @RequestParam("avatar") String avatar){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String,Object> resultMap = cusUserService.saveUserAvatar(userId,avatar);
        if (ResultUtil.getSuccess(resultMap)) {
            JsonObject user = webMobileLoginUtil.getLoginUser(request);
            user.addProperty("avatar",avatar);
            String sid = WebUtils.getCookie(request, CommonConstants.USER_SINGLE_ID);
            //重新更新缓存
            userLoginService.updateUserLoginCache(sid,user.toString());
        }
        return resultMap;
    }

    /**
     * 账户安全
     * @param request
     * @return
     */
    @RequestMapping("/ajax/securityOfAccounts")
    public String newSecurityOfAccounts(HttpServletRequest request,Model model){
        BigDecimal userId= webMobileLoginUtil.getLoginUserId(request);
        Map<String,Object> user = cusUserService.userInfo(userId,false,false,false,false,false,false,false);
        model.addAttribute("user",user);
        return resultPage("/user/center/myInfo/u-account-security");
    }

    /**
     * 修改用户密码
     *
     * @param nowPwd     原密码
     * @param newPwd     新密码
     * @param confirmPwd 确认密码
     * @return Map<String   ,   Object>
     */
    @RequestMapping("/updateUserPwd")
    @ResponseBody
    public Map<String, Object> updateUserPwd(HttpServletRequest request,
                                             @RequestParam(value = "nowPwd") String nowPwd,
                                             @RequestParam(value = "newPwd") String newPwd,
                                             @RequestParam(value = "confirmPwd") String confirmPwd,
                                             @RequestParam("sign") String sign) throws Exception {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String,Object> resultMap = cusUserService.updateUserPwd(userId, nowPwd, newPwd, confirmPwd,sign);
        if(!ResultUtil.getSuccess(resultMap)){
            Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
            resultMap.put("keyMap",keyMap);
        }
        return resultMap;
    }

    /**
     * 我的账号
     *
     * @param request
     * @return
     */
    @RequestMapping("/myAccount")
    public String ucMyAccount(HttpServletRequest request,Model model) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String,Object> userAccount = cusUserAccountService.userAccountInfo(userId,false);
        model.addAttribute("userAccount", userAccount);
        model.addAttribute("accountHistoryTypeList", AccountHistoryType.values());
        return resultPage("/user/center/myAccount/u-myAccount");
    }

    /**
     * 账号列表
     *
     * @param request
     * @return
     */
    @RequestMapping("/ajax/queryUserAccountHistories")
    public String queryUserAccountHistories(Model model,
                                               @RequestBody Map<String,Object> params,
                                               HttpServletRequest request,
                                               @RequestParam(value = "currentPage",required = false,defaultValue = "1") Integer currentPage) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        params.put("userId",userId);
        Map<String,Object> dataMap = cusUserAccountHistoryService.userAccountHistoryListPage(params, currentPage,true);
        model.addAttribute("dataMap",dataMap);
        return resultPage("/user/center/myAccount/u-ajax-myAccount");
    }




    /**
     * 我的积分
     * @param request
     * @return
     */
    @RequestMapping("/myInteger")
    public String myInteger(Model model,HttpServletRequest request)throws Exception{

        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String,Object> parmas = new HashMap<>();
        parmas.put("userId",userId);
        List<Map<String,Object>> userIntegralRecords = cusUserIntegralRecordService.queryCusUserIntegralRecordList(null,null,parmas,false);
        Integer yesterday=0;//昨天收取
        Integer consumption=0;//消耗积分
        if(ObjectUtils.isNotEmpty(userIntegralRecords)){
            for (Map<String,Object> _userIntegralRecord:userIntegralRecords){
                if((Integer)_userIntegralRecord.get("recordType")==2){
                    SimpleDateFormat  formatter= new SimpleDateFormat( "yyyy-MM-dd ");
                    String date =(String) _userIntegralRecord.get("createTime");
                    Date _date = formatter.parse(date);
                    if(DateUtils.daysBeforeNow(_date)==-1){
                        yesterday+=(Integer) _userIntegralRecord.get("score");
                    }
                }else{
                    consumption+=(Integer) _userIntegralRecord.get("score");
                }
            }
        }
        Map<String,Object> userIntegral=cusUserIntegralService.queryUserIntegralByUserId(userId);
        request.setAttribute("yesterday",yesterday);
        request.setAttribute("consumption",consumption);
        model.addAttribute("userIntegral",userIntegral);
        model.addAttribute("qrCodeUrl",contextPath+"/mobile/uc/integral/integralIndex");

        return resultPage("/user/center/myAccount/u-myIntegral");
    }

    /**
     * 我的积分获取记录列表
     *
     * @param request
     * @return
     */
    @RequestMapping("/ajax/userIntegralList")
    public String ajaxUserIntegralList(Model model,HttpServletRequest request,
                                       @RequestParam(value = "currentPage",required = false,defaultValue = "1") Integer currentPage,
                                       @RequestBody CusUserIntegralRecord userIntegralRecord) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        userIntegralRecord.setUserId(userId);
        Map<String,Object> dataMap = cusUserIntegralRecordService.queryCusUserIntegralRecordListPage(currentPage, userIntegralRecord,false);
        model.addAttribute("dataMap",dataMap);
        return resultPage("/user/center/myAccount/u-ajax-myIntegral");
    }



    /**
     * 我的作业
     * @param request
     * @return
     */
    @RequestMapping("/myAssingmets")
    public String ucNewMyAssingmets(Model model,HttpServletRequest request){
        return resultPage("/user/center/u-assingmets");
    }

    /**
     * 我的推广
     * @param model
     * @return
     */
    @RequestMapping("/extensionHome")
    public String extensionNewHome(Model model){
        //H5站二维码
        TreeMap<String,String> h5MobileMap = sysConfigService.getSysConfigContext(ConfigName.H5AMOBILE);
        model.addAttribute("h5MobileMap",h5MobileMap);
        //小程序二维码
        TreeMap<String,String> smallAppMap = sysConfigService.getSysConfigContext(ConfigName.SMALLAPP);
        model.addAttribute("smallAppMap",smallAppMap);
        //App下载二维码
        TreeMap<String,String> appDowMap = sysConfigService.getSysConfigContext(ConfigName.APPDOW);
        model.addAttribute("appDowMap",appDowMap);
        return resultPage("/user/center/extension/u-extension-home");
    }

    /**
     * 我的数据
     * @param request
     * @return
     */
    @RequestMapping("/myDates")
    public String myDates(HttpServletRequest request){
        return resultPage("/user/center/dates/u-dates");
    }

    /**
     * 我的数据
     * @param
     * @return
     */
    @RequestMapping("/isUserMember")
    @ResponseBody
    public Map isUserMember(HttpServletRequest request){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        boolean isMemberUser =  cusUserMemberBuyRecordService.checkUserUseMemberPrice(userId);
        return ResultUtil.SUCCESS(isMemberUser)  ;
    }
}

